from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed

from app01.models import UserToken


class MyAuthentication(BaseAuthentication):
    def authenticate(self, request):
        # 书写认证逻辑
        # 认证成功 返回两个值 user和token
        # 认证失败 抛出 AuthenticationFailed异常
        token = request.GET.get('token')
        if token:
            user_token = UserToken.objects.filter(token=token).first()
            if user_token:
                return user_token.user, token
            else:
                raise AuthenticationFailed('认证失败')
        else:
            raise AuthenticationFailed('请携带token')
